package com.Algorithm.binarysearchnorecusion;

import java.util.Arrays;

/**
 * @author shkstart
 * @create 2021-08-18 21:58
 */
public class BinarySearchNoRecur {
    public static void main(String[] args) {
     int arr[]={6,4,7,3,70,3,677,0,-2};
        Arrays.sort(arr);
        int index = binarySearch(arr, 33);
        System.out.println(index);
    }
    //非递归的二分法查找

    /**
     *
     * @param arr 要查找的数组，唯一麻烦的是要排序好的
     * @param targe 查找的目标
     * @return 若是没有找到，那就返回-1
     */
    public static int binarySearch(int[] arr,int targe) {
        int left = 0;
        int right = arr.length - 1;
        //循环的条件
        while (left <= right) {
            int mid = (left + right) / 2;
            if (arr[mid] == targe) {
                return mid;
            } else if (arr[mid] > targe) {
                right = mid - 1;
            } else {
                left = mid + 1;
            }

        }
        return -1;
    }
}
